#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFSIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

void read_childproc(int sig) {
    int status;
    pid_t id = waitpid(-1, &status, WNOHANG);
    printf("Removed proc id: %d \n", id);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("usage : %s <port> \n", argv[0]);
        return 0;
    }
    int serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    // address
    struct sockaddr_in serv_addr, client_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(atoi(argv[1]));

    // handle函数
    struct sigaction act;
    act.sa_handler = read_childproc;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    int state = sigaction(SIGCHLD, &act, 0);

    if (bind(serv_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
        error_handling("bind() error");
    if (listen(serv_sock, 5) == -1)
        error_handling("listen() error");
    int buf[BUFSIZE];

    int fd[2];
    pipe(fd);
    pid_t pid = fork();
    // 一个子进程用于处理上传文件操作
    if (pid == 0) {
        FILE *fp = fopen("b.txt", "wt");
        char msg[BUFSIZE];
        for (int i = 0; i < 10; i++) {
            // 先从管道读取文件
            int len = read(fd[0], msg, BUFSIZE);
            printf("msg = %slen = %d\n", msg, len);
            fwrite((void *)msg, 1, len, fp);         
        }
        fclose(fp);
        return 0;
    }
    while (1) {
        int addr_sz = sizeof(client_addr);
        int connfd = accept(serv_sock, (struct sockaddr *)&client_addr, &addr_sz);
        if (connfd != -1)
            puts("new client connected");
        pid_t pid = fork();
        if (pid == -1) {
            close(connfd);
            continue;
        } else if (pid == 0) {
            // 子进程关闭用于监听的socket,只用于通信
            close(serv_sock);
            int str_len = 0;
            while (str_len = read(connfd, buf, BUFSIZE)) {
                write(connfd, buf, str_len);
                write(fd[1], buf, str_len);
            }
            close(connfd);
            puts("client disconnected...");
            return 0;
        } else {
            // 父进程关闭用于通信的socket
            close(connfd);
        }
    }
    // 最后关闭用于监听的socket
    close(serv_sock);
    return 0;
}